package com.sebscape.sebcms.security.actions;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.sebscape.sebcms.Constants;
import com.sebscape.sebcms.security.domain.User;
import com.sebscape.sebcms.security.persistence.UserDao;
import com.sebscape.sebcms.tools.Utils;

public class AuthenticateActions extends ActionSupport {
	
	private static final long serialVersionUID = 1161872640975465232L;
	private static Log log = LogFactory.getLog( AuthenticateActions.class );
	
	private List<String> errorList = new ArrayList<String>();
	public static final String DENIED = "denied";
	public static final String FALLBACK_SUCCESS_URL = "/home";
	private String defaultLandingUrl = null;
	private String uri = null;
	
	/**
	 * Set as a param in the Struts config.
	 * @param url
	 */
	public void setDefaultLandingUrl( String url ){
		this.defaultLandingUrl = url;
	}

	/**
	 * Read by the action-forward in the struts config.
	 * @return
	 */
	public String getUri(){
		return this.uri;
	}
	
	public List<String> getErrorList(){
		return this.errorList;
	}
	
	/**
	 * Struts action calls this method to authenticate the user login form.
	 * It looks for j_username and j_password in the Request scope. It will
	 * also check for a optional j_uri for forwarding.
	 * @return
	 */
	public String login(){
		log.debug("login begin.");
		Boolean bInError = Boolean.FALSE;
		// reset the errorList;
		errorList.clear();
		String username = Utils.getRequestValue(ServletActionContext.getRequest(), "j_username", null);
		log.debug("username "+username);
		String password = Utils.getRequestValue(ServletActionContext.getRequest(), "j_password", null);
		log.debug("password "+password);
		// check for empty fields.
		if( Utils.isEmpty( username ) ){
			errorList.add( "Please enter a <span class=\"field_name\">username</span>." );
			bInError = Boolean.TRUE;
			log.debug("username empty - set inError.");
		}
		if( Utils.isEmpty( password ) ){
			errorList.add( "Please enter a <span class=\"field_name\">password</span>." );
			bInError = Boolean.TRUE;
			log.debug("password empty - set inError.");
		}
		// if we have username and password then continue.
		if( !bInError ){
			// get the dao.
			log.debug("get dao");
			UserDao dao = new UserDao();
	        try {
	        	// attempt to fetch user from database.
	        	/*String filter = "name=='"+username + "' && password=='" + password + "'";
	        	log.debug("find using filter: " + filter );
	        	List<User> users = dao.findByFilter(filter );*/
	        	User user = dao.findByLogin(username, password);
	            //if( users != null && users.size() > 0 ){
	        	if( user != null ){
	            	handleUserValidated( user, dao );
	            } else {
	            	errorList.add( "Invalid username/password combination." );
	            	bInError = Boolean.TRUE;
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	            errorList.add( "Internal Error: " + e.getMessage() +"."  );
	            bInError = Boolean.TRUE;
	        }
		}
        if( bInError ){
        	ServletActionContext.getRequest().setAttribute( "errorList", errorList );
        	log.debug( "errorList set with size = " + errorList.size() );
        	return DENIED;
        } else {
        	this.uri = this.computeSuccessUrl();
        	return SUCCESS;
        }
	}

	/**
	 * Check the session for j_uri. If not there, check the j_uri form field. If not
	 * there go to the default in the Struts-action-param. If all else fails, call
	 * FALLBACK_SUCCESS_URL.
	 * @param request
	 * @return
	 **/
	private String computeSuccessUrl(){
		String url = (String) ServletActionContext.getRequest().getSession().getAttribute( "j_uri" );
		if( Utils.isEmpty( url ) ){
			//log.debug( "juri is empty in session, so check request...");
			url = Utils.getRequestValue(ServletActionContext.getRequest(), "j_uri", defaultLandingUrl );
			//log.debug(" url is now: " + url );
		}
		if( Utils.isEmpty( url ) ){
			url = FALLBACK_SUCCESS_URL;
		}
		//log.debug("returning URL: " + url );
		return url;
	}

	/**
	 * Add to this method any processing you would like to do with a user who has
	 * been successfully logged in.
	 * @param user
	 */
    private void handleUserValidated( User user, UserDao dao ){
    	log.debug("Begin handleUserVlaidated");
    	// get a copy of this user with groups and roles set.
    	//user = dao.load( user.getId() );
    	// put the user in the session and request.
    	ServletActionContext.getRequest().setAttribute(Constants.ATTRIB_CURRENT_USER, user);
    	ServletActionContext.getRequest().getSession().setAttribute(Constants.ATTRIB_CURRENT_USER, user);
    }
    
    /**
     * Handle logout - invalidate the session.
     * @return
     */
    public String logout(){
    	ServletActionContext.getRequest().getSession().invalidate();
    	return SUCCESS;
    }

}
